package com.jse.oo.design.pattern.behavioral.observer.publish;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class InputLoop implements Publisher<String> {
	private List<Subscriber<String>> subscribers;

	private InputLoop() {
		subscribers = new ArrayList<Subscriber<String>>();
	}

	public static InputLoop create() {
		return new InputLoop();
	}

	@Override
	// register subscriber
	public void subscribe(Subscriber<String> subscriber) {
		if (!subscribers.contains(subscriber)) {
			subscribers.add(subscriber);
		}
	}

	@Override
	// Notify all subscribers
	public void publish(String data) {
		for (Subscriber<String> sub : subscribers) {
			sub.getPublication(data);
		}
	}

	public static String getInput() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String response = "";

		try {
			response = br.readLine();
			if (response == null) {
				return "";
			}
		} catch (IOException e) {
		}
		return response;
	}

	public void loop() {
		while (true) {
			System.out.println("> ");
			String s = getInput();
			publish(s);
		}
	}
}
